package com.samphanie.ane.common.exception;

import com.samphanie.ane.common.utils.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2021/3/11 20:17
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler
    public CommonResult<ResultCode> handleException(ApiException exception) {

        if (exception.getErrorCode() != null) {
            return CommonResult.failed(exception.getErrorCode());
        } else {
            return CommonResult.failed(exception.getMessage());
        }

    }

    /**
     * 统一表单验证
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<ResultCode> handleNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();

        return CommonResult.failed(
                Objects.requireNonNull(bindingResult.getFieldError()).getField()
                        + bindingResult.getFieldError().getDefaultMessage());
    }


}
